﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace SourcePacker
{
    public partial class MainForm : Form
    {
        Engine Engine { get; set; }

        public MainForm()
        {
            InitializeComponent();
            Engine = new Engine();
            listViewConditionalSourceFolders.MouseClick += ListViewConditionalSourceFolders_MouseClick;
        }

        private void ListViewConditionalSourceFolders_MouseClick(object sender, MouseEventArgs e)
        {
            var hitTestInfo = listViewConditionalSourceFolders.HitTest(e.Location);

            if (hitTestInfo.Item != null)
            {
                textBox6.Text = hitTestInfo.Item.Text;
                textBox2.Text = ((KeyValuePair<string, string>)hitTestInfo.Item.Tag).Key;
                textBox5.Text = ((KeyValuePair<string, string>)hitTestInfo.Item.Tag).Value;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //SourceFile sourceFile = new SourceFile(@"C:\Users\tinop\Desktop\abc.h");
            //IncludeLocator locator = new IncludeLocator(sourceFile);

            //var results = locator.Results;

            //List<string> list = new List<string>();

            //foreach (var result in results)
            //    list.Add(sourceFile.Text.Substring(result.Key, result.Value.Value - result.Key));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();

            dialog.Title = "请选择输出头文件：";
            dialog.AddExtension = true;
            dialog.DefaultExt =".h";
            dialog.Filter = "头文件(*.h;*.hpp)|*.h;*.hpp|所有文件(*.*)|*.*";

            dialog.RestoreDirectory = false;
            dialog.OverwritePrompt = true;

            if (dialog.ShowDialog() == DialogResult.OK)
                textBox1.Text = dialog.FileName;

            //if (comboBox2.SelectedIndex == 2)
            //{
            //    FolderBrowserDialog dialog = new FolderBrowserDialog();
            //    dialog.Description = "请选择源文件路径";

            //    if (dialog.ShowDialog() == DialogResult.OK)
            //    {
            //        textBox1.Text = dialog.SelectedPath;
            //    }
            //}
            //else
            //{
            //OpenFileDialog dialog = new OpenFileDialog();
            //dialog.CheckFileExists = true;
            //dialog.DereferenceLinks = true;
            //dialog.Filter = comboBox2.SelectedIndex == 0 ?
            //    "头文件(*.h;*.hpp)|*.h;*.hpp|所有文件(*.*)|*.*" :
            //    "源文件(*.c;*.cpp)|*.c;*.cpp|所有文件(*.*)|*.*";
            //dialog.Multiselect = false;
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    textBox1.Text = dialog.FileName;
            //}
            //}
        }

        //private void button8_Click(object sender, EventArgs e)
        //{
        //    Forms.AdditionalIncludesForm dialog = new Forms.AdditionalIncludesForm(settings.AdditionalIncludeFolders);

        //    if (dialog.ShowDialog() == DialogResult.OK)
        //    {
        //        settings.AdditionalIncludeFolders = dialog.AdditionalIncludes;
        //    }
        //}

        private void button9_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();

            dialog.Title = "请选择输出源文件：";
            dialog.AddExtension = true;
            dialog.DefaultExt = ".c";
            dialog.Filter = "源文件(*.c;*.cpp)|*.c;*.cpp|所有文件(*.*)|*.*";

            dialog.RestoreDirectory = false;
            dialog.OverwritePrompt = true;

            if (dialog.ShowDialog() == DialogResult.OK)
                textBox4.Text = dialog.FileName;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked) checkBox3.Checked = false;
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked) checkBox2.Checked = false;
        }

        string[] getListViewItems(ListView listView)
        {
            string[] result = new string[] { };
            Array.Resize(ref result, listView.Items.Count);

            for (int i = 0; i < result.Length; ++i)
                result[i] = listView.Items[i].Text;

            return result;
        }

        Dictionary<string, KeyValuePair<string, string>> getConditionalSourceFolders()
        {
            Dictionary<string, KeyValuePair<string, string>> result =
                new Dictionary<string, KeyValuePair<string, string>>();

            for (int i = 0; i < listViewConditionalSourceFolders.Items.Count; ++i)
                result.Add(listViewConditionalSourceFolders.Items[i].Text,
                    (KeyValuePair<string, string>)listViewConditionalSourceFolders.Items[i].Tag);

            return result;
        }

        bool listViewContains(ListView listView, string key)
        {
            foreach (ListViewItem item in listView.Items)
                if (item.Text == key) return true;

            return false;
        }


        private void button7_Click(object sender, EventArgs e)
        {
            if (textBox1.TextLength == 0 && textBox4.TextLength == 0)
            {
                MessageBox.Show("请输出头文件和源文件至少指定一个！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //ExportHeaderFiles = new string[] { };
            //SourceFolders = new string[] { };
            //CondionalSourceFolders = new Dictionary<string, KeyValuePair<string, string>>();
            //AdditionalIncludeFolders = new string[] { };

            //SourceExtensions = new string[] { ".c", ".cpp" };

            //OutputHeaderFile = "";
            //OutputSourceFile = "";

            //ReplaceSystemInclude = true;
            //IncludeExportHeaderIfNeeded = true;
            //AppendFileSplitter = false;
            //CompactSource = true;


            Engine.Settings.ExportHeaderFiles = getListViewItems(listViewExportHeaders);
            Engine.Settings.SourceFolders = getListViewItems(listViewSourceFolders);
            Engine.Settings.CondionalSourceFolders = getConditionalSourceFolders();
            Engine.Settings.AdditionalIncludeFolders = getListViewItems(listViewAdditionalIncludeFolders);

            Engine.Settings.SourceExtensions = textBox3.Text.Split(';');

            Engine.Settings.OutputHeaderFile = textBox1.Text;
            Engine.Settings.OutputSourceFile = textBox4.Text;

            Engine.Settings.ReplaceSystemInclude = checkBox1.Checked;
            Engine.Settings.IncludeExportHeaderIfNeeded = checkBox4.Checked;
            Engine.Settings.AppendFileSplitter = checkBox3.Checked;
            Engine.Settings.CompactSource = checkBox2.Checked;

            Engine.execute();

            long outputHeaderFileSize = Engine.Settings.OutputHeaderFile.Length == 0 ? 0 :
                new FileInfo(Engine.Settings.OutputHeaderFile).Length;

            long outputSourceFileSize = Engine.Settings.OutputSourceFile.Length == 0 ? 0 :
                new FileInfo(Engine.Settings.OutputSourceFile).Length;
            
            label1.Text = "" + (Engine.SourceContainer.ExportHeadersTotalSize / 1024) + " KB（" + Engine.SourceContainer.ExportHeaders.Count + " 个头文件） => " + (outputHeaderFileSize / 1024) + " KB\n" +
                "" + (Engine.SourceContainer.SourcesTotalSize / 1024) + " KB（" + Engine.SourceContainer.Sources.Count + " 个头文件） => " + (outputSourceFileSize / 1024) + " KB";

            MessageBox.Show("合并完成！");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空导出头文件列表？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                listViewExportHeaders.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.CheckFileExists = true;
            dialog.DereferenceLinks = true;

            dialog.Filter = "头文件(*.h;*.hpp)|*.h;*.hpp|所有文件(*.*)|*.*";
            dialog.Multiselect = true;

            if (dialog.ShowDialog() == DialogResult.OK)
                foreach (var item in dialog.FileNames)
                    if (!listViewContains(listViewExportHeaders, item))
                        listViewExportHeaders.Items.Add(item);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewExportHeaders.SelectedItems)
                listViewExportHeaders.Items.Remove(item);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空源文件目录列表？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                listViewSourceFolders.Clear();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择源文件目录";
            dialog.ShowNewFolderButton = false;

            if (dialog.ShowDialog() == DialogResult.OK
                && !listViewContains(listViewSourceFolders, dialog.SelectedPath))
                listViewSourceFolders.Items.Add(dialog.SelectedPath);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewSourceFolders.SelectedItems)
                listViewSourceFolders.Items.Remove(item);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空附加包含目录列表？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                listViewAdditionalIncludeFolders.Clear();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择附加包含目录";
            dialog.ShowNewFolderButton = false;

            if (dialog.ShowDialog() == DialogResult.OK
                && !listViewContains(listViewAdditionalIncludeFolders, dialog.SelectedPath))
                listViewAdditionalIncludeFolders.Items.Add(dialog.SelectedPath);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewAdditionalIncludeFolders.SelectedItems)
                listViewAdditionalIncludeFolders.Items.Remove(item);
        }

        private void button12_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空条件源代码目录列表？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                listViewConditionalSourceFolders.Clear();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            if (textBox6.TextLength == 0)
            {
                MessageBox.Show("请先选择条件源码目录！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            if (listViewContains(listViewConditionalSourceFolders, textBox6.Text))
            {
                MessageBox.Show("目录已添加！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ListViewItem item = new ListViewItem(textBox6.Text);
            item.Tag = new KeyValuePair<string, string>(textBox2.Text, textBox5.Text);
            listViewConditionalSourceFolders.Items.Add(item);
        }

        private void button17_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private void button18_Click(object sender, EventArgs e)
        {
            textBox4.Clear();
        }

        private void button16_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择条件源码目录";
            dialog.ShowNewFolderButton = false;

            if (dialog.ShowDialog() == DialogResult.OK)
                textBox6.Text = dialog.SelectedPath;
        }

        private void button10_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewConditionalSourceFolders.SelectedItems)
                listViewConditionalSourceFolders.Items.Remove(item);
        }

        private void button19_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择头文件目录";
            dialog.ShowNewFolderButton = false;

            if (dialog.ShowDialog() != DialogResult.OK) return;

            string[] headerExtensions = { ".h", ".hpp" };
            foreach (var item in Directory.GetFiles(dialog.SelectedPath, "*.*", SearchOption.AllDirectories))
                if (item != "." && item != ".." &&
                    Array.IndexOf(headerExtensions, Path.GetExtension(item)) >= 0)
                    if (!listViewContains(listViewExportHeaders, item))
                        listViewExportHeaders.Items.Add(item);
        }
    }
}
